<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */


/**
 * Smarty truncate modifier plugin
 *
 * Type:     modifier<br>
 * Name:     truncate<br>
 * Purpose:  Truncate a string to a certain length if necessary,
 *           optionally splitting in the middle of a word, and
 *           appending the $etc string or inserting $etc into the middle.
 * @link http://smarty.php.net/manual/en/language.modifier.truncate.php
 *          truncate (Smarty online manual)
 * @author   Monte Ohrt <monte at ohrt dot com>
 * @param string
 * @param integer
 * @param string
 * @param boolean
 * @param boolean
 * @return string
 */
function smarty_modifier_truncate($string, $length = 80, $etc = '...',
                                  $break_words = false, $middle = false)
{
    if ($length == 0)
        return '';

    if (strlen($string) > $length) {
        $length -= strlen($etc);
        if (!$break_words && !$middle) {
            $string = preg_replace('/\s+?(\S+)?$/', '', mxx_truncate_utf8substr($string, 0, $length+1));
        }
        if(!$middle) {
            return mxx_truncate_utf8substr($string, 0, $length).$etc;
        } else {
            return mxx_truncate_utf8substr($string, 0, $length/2) . $etc . mxx_truncate_utf8substr($string, -$length/2);
        }
    } else {
        return $string;
    }
}

function mxx_truncate_utf8substr($str, $start, $length = 0) {
	$strlen = strlen($str);
	if( $start < 0 ) {
		$start = $strlen + $start;
	}
	if( $length == 0 ) {
		$length = max(0, $strlen - $start);
	}
	if( $strlen > $start + $length + 1 ) {
		$strlen = $start + $length;
	}
	
	$tmpstr = '';
	for($i=$start; $i<$strlen; $i++) {
		if( ord(substr($str, $i, 1)) > 127 ) {//0xa0
			$tmpstr .= substr($str, $i, 3);
			$i = $i + 2;
		} else {
			$tmpstr .= substr($str, $i, 1);
		}
	}
	
	return $tmpstr;
}

/* vim: set expandtab: */

?>
